package cn.butcher21.controller.login;

import cn.butcher21.dao.DaoUser;
import cn.butcher21.dao.DaoWorkImpl.DaoUserImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        Map<String, Object> map = new HashMap<>();
        DaoUser daoUser = new DaoUserImpl();
        try {
            String[] check = daoUser.check(username, password);
            if (check != null) {
                HttpSession session = request.getSession();
                session.setAttribute("userid", check[0]);
                if (remember != null) {
                    Cookie cookie1 = new Cookie("username", username);
                    Cookie cookie2 = new Cookie("password", password);
                    cookie1.setMaxAge(1000000000);
                    cookie2.setMaxAge(1000000000);
                    cookie1.setPath("/");
                    cookie2.setPath("/");
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                }
                map.put("status", 1);
                if (check[1].equals("0")) {
                    map.put("href", "index.html");
                } else {
                    map.put("href", "manager.html");
                }

            } else {
                map.put("status", 0);
                map.put("msg", "有可能是小组名或密码错了");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        String json = gson.toJson(map);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(json);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
